import { AnimationFrame } from '../animation/animation-frame';


/**
 * 帧率计算
 */
class FrameRate {

    private static _record = new Float32Array(60);
    private static _req = {};
    private static _idx = -1;

    /**
     * 获取帧率（每秒）
     */
    public static get fps(): number {
        const dpf = this.dpf;
        return 1000 / dpf;
    }

    /**
     * 获取帧时长（毫秒）
     */
    public static get dpf(): number {
        this.begin();
        if (this._idx < 0) return 1000;
        const c = this._record[this._idx];
        const p = this._record[(this._idx + 1) % 60];
        return (c - p) / 59;
    }

    /**
     * 停止采样并重置
     */
    public static dispose(): void {
        AnimationFrame.cancel(this._req);
        this._idx = -1;
        this._record.fill(0);
    }

    /**
     * 开始采样
     */
    private static begin(): void {
        if (this._idx < 0) {
            AnimationFrame.request(() => {
                FrameRate._idx++;
                FrameRate._idx %= 60;
                FrameRate._record[FrameRate._idx] = performance.now();
            }, 0, 1000, this._req);
        }
    }

}


export { FrameRate };